package com.cloudmusic.controller;

import java.io.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.alibaba.fastjson.JSONObject;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import com.cloudmusic.service.MusicService;
import org.springframework.web.bind.annotation.ResponseBody;

@Controller
@RequestMapping("music/play")
public class MusicController {

	private Logger logger=Logger.getLogger(this.getClass());

	@Autowired
	MusicService musicservice;
	
	@RequestMapping("stream")
	public void playmusic(String sid,HttpServletRequest request,HttpServletResponse response) throws IOException {
		
		String musiclocal = musicservice.selectMusicLocal(sid);
		File file = new File(musiclocal);
		FileInputStream fis=new FileInputStream(file);
		logger.info("播放文件："+file.getAbsolutePath());
		OutputStream os = response.getOutputStream();
		BufferedOutputStream bos = new BufferedOutputStream(os);
		//使得流文件可控制进度
		long length = file.length();
		String range = request.getHeader("Range");
		String[] rs = range.split("\\=");
		range = rs[1].split("\\-")[0];
		response.addHeader("Accept-Ranges", "bytes");
		response.addHeader("Content-Length", length + "");
		response.addHeader("Content-Range", "bytes " + range + "-" + length + "/" + length);
		response.addHeader("Content-Type", "audio/mp3;charset=UTF-8");
        byte[] data=new byte[1024*4];
        int len=0;
        while ((len=fis.read(data))!=-1)
        {
        	bos.write(data);
        }
        bos.flush();
		os.close();
        bos.close();
	}

	@RequestMapping("filename")
	@ResponseBody
	public JSONObject selectmusicname(String sid){
		JSONObject json = musicservice.selectMusicName(sid);
		return json;
	}
	
	
	
}
